package cvut.cz.via.android;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ToggleButton;
import cvut.cz.via.android.courses.Course;

public class CourseInfoActivity extends Activity {
	
	private TextView name;
	private TextView code;
	private TextView popis;
	private ToggleButton subscribed;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.course_info_activity);		
		setUpView();
	}

	private void setUpView() {
		StudyMaterialsApplication sma = getStudyMaterialsApplication();
		Course course = sma.actualCourse;
		
		name = (TextView) findViewById(R.id.course_name_label);
		code = (TextView) findViewById(R.id.course_code_label);
		popis = (TextView) findViewById(R.id.course_popis_label);
		subscribed = (ToggleButton) findViewById(R.id.course_info_activity_subscribe_button);
		
		name.setText(course.getName());
		code.setText(course.getCode());
		popis.setText(course.getPopis());
		subscribed.setChecked(sma.user.getSubscribedCourses().contains(course.getCode()));
		
	}
	
	private StudyMaterialsApplication getStudyMaterialsApplication() {
		StudyMaterialsApplication sma = (StudyMaterialsApplication)getApplication();
		return sma;
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		StudyMaterialsApplication sma = getStudyMaterialsApplication();
		Course course = sma.actualCourse;
		if(subscribed.isChecked() == true) {
			if(!sma.user.getSubscribedCourses().contains(course.getCode())){
				sma.user.getSubscribedCourses().add(course.getCode());
			}
		} else {
			sma.user.getSubscribedCourses().remove(course.getCode());
		}
		ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
		ObjectOutput out;
		try {
			out = new ObjectOutputStream(bos);		
			out.writeObject(sma.user);
			byte[] buf = bos.toByteArray();
	        FileOutputStream fos = this.openFileOutput("config.dat", Context.MODE_PRIVATE);
	        fos.write(buf);
	        fos.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        Log.d("COURSES_SAVED", sma.user.toString());
		super.onDestroy();
	}
	
	

}
